// pages/another/another.js
const app = getApp();
Page({
  data: {
    checkbox:[1],
    totalAnother:'0.00',
    endDate:['结束时间'],
    startDate:['开始时间'],
    nianJin:[''],
    bussinessHealth:[''],
    yangLaoJin:[''],
    other:[''],
    calDate:"",
    nowYear:"",
    
    // index2:0
  },
  /**
 * 
 * @param {String} dateStr1 
 * @param {String} dateStr2 
 */
compareDate:function(dateStr1,dateStr2){
  const date1 = new Date(dateStr1);
  const date2 = new Date(dateStr2);
  if (date1 > date2) {
      return 1;
  } else if (date1 < date2) {
      return 2;
  } else {
      return 0;
  }
},

/**
 * 
 * @param {String} startStr 
 * @param {String} endStr 
 */
calRentMonth:function(startStr,endStr){
  var end = endStr;
  var start = startStr;
  var cal = this.data.calDate;
  var result = 0;
  //传入其他字符串，直接返回0
  if(end.indexOf("-") === -1 || start.indexOf("-") === -1){
    return 0;
  }
  var startComCal = this.compareDate(cal,start);
  var calComEnd = this.compareDate(cal,end);
  // start <= cal < end
  if(startComCal <= 1 && calComEnd === 2){
     if(start.slice(0,4) !== cal.slice(0,4)){
      result = Number(cal.slice(-2));
     }else{
      result = Number(cal.slice(-2)) - Number(start.slice(-2)) + 1;
     }
     return result;
    // end 小于等于 cal的情况
  }else if(calComEnd <= 1)
  {
    // end跨年，只能是往前面算
    if(end.slice(0,4) !== cal.slice(0,4)){
      result = 0;
    }
    // end不跨年
    else{
      // start跨年
      if(start.slice(0,4) !== cal.slice(0,4)){
         result = Number(end.slice(-2));
      }
      // start不跨年
      else{
        result = Number(end.slice(-2)) - Number(start.slice(-2)) + 1;
      }
    }
     return result;
  }
  else{
     result = 0;
  }
  return result;
},

  
  insert(e){
    var cb = this.data.checkbox;
    var start = this.data.startDate;
    var end = this.data.endDate;
    var nianJin = this.data.nianJin;
    var bussinessHealth = this.data.bussinessHealth;
    var yangLaoJin = this.data.yangLaoJin;
    var other = this.data.other;
    start.push('开始时间');
    cb.push(cb.length+1);
    end.push('结束时间');
    nianJin.push('');
    bussinessHealth.push('');
    yangLaoJin.push('');
    other.push('');
    this.setData({startDate:start,endDate:end,checkbox:cb,nianJin:nianJin,bussinessHealth:bussinessHealth,yangLaoJin:yangLaoJin,other:other});
  },

  delBind(e){
    var cb = this.data.checkbox;
    var start = this.data.startDate;
    var end = this.data.endDate;
    var nianJin = this.data.nianJin;
    var bussinessHealth = this.data.bussinessHealth;
    var yangLaoJin = this.data.yangLaoJin;
    var other = this.data.other;
    start.pop();
    cb.pop();
    end.pop();
    nianJin.pop();
    bussinessHealth.pop();
    yangLaoJin.pop();
    other.pop();
    this.setData({startDate:start,endDate:end,checkbox:cb,nianJin:nianJin,bussinessHealth:bussinessHealth,yangLaoJin:yangLaoJin,other:other});
  },

  //unfinished
  /**
   * checkbox:[1],
    totalAnother:'0.00',
    endDate:['结束时间'],
    startDate:['开始时间'],
    nianJin:[''],
    bussinessHealth:[''],
    yangLaoJin:[''],
    other:[''],
    calDate:"",
    nowYear:"",
   */
  calOtherCount(){
    var bussinessHealth = this.data.bussinessHealth;
    var nianJin = this.data.nianJin;
    var yangLaoJin = this.data.yangLaoJin;
    var other = this.data.other;
    var endDate = this.data.endDate;
    var startDate = this.data.startDate;
    var result = 0,months = 0,temp1 = 0,temp2 = 0,temp3 = 0,temp4 = 0;
    var head = '',tail = '',tagT = '1900-01',tagH = '1900-01';
    for(var i = 0;i < startDate.length;i++){
      if(startDate[i].indexOf("-") === -1 || endDate[i].indexOf("-") === -1){
        return -1.0
      }
      months = this.calRentMonth(startDate[i],endDate[i])
      if(months === 0){
        // 不好好填的都不算数，直接是0。
        continue;
      }
      if(nianJin[i] !== ''){
        temp1 = Number(nianJin[i]);
      }
      if(bussinessHealth[i] !== ''){
        temp2 = (Number(bussinessHealth[i]) > 200?200:Number(bussinessHealth[i]));
      }
      if(yangLaoJin[i] !== ''){
        temp3 = (Number(yangLaoJin[i]) > 1000?1000:Number(yangLaoJin[i]));
      }
      if(other[i] !== ''){
        temp4 = Number(other[i]);
      }
      tail = endDate[i],head = startDate[i];
      if(this.compareDate(tail,tagH) === 2 || this.compareDate(tagT,head) === 2){
        result = result + months * (temp1 + temp2 + temp3 + temp4);
      }else{
        //有时间区间重复，直接返回-1，提示用户重新填写。
        return -1.0
      }
      tagH = startDate[i],tagT = endDate[i];
      temp1 = 0,temp2 = 0,temp3 = 0,temp4 = 0;
    }
    result = result.toFixed(2);
    this.setData({totalAnother:result});
    return result;
  },

  bindStartDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var start = this.data.startDate;
    start[nowIdx] = value;
    this.setData({startDate:start});
  },

  bindEndDateChange(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var start = this.data.startDate;
    if(start[nowIdx].indexOf("-") === -1){
      wx.showToast({
        title: '请先输入开始时间！',
        icon:'none'
      });
      return;
    }
    var end = this.data.endDate;
    end[nowIdx] = value;
    this.setData({endDate:end});
  },
  
  onNianJin(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var nianJin = this.data.nianJin;
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      nianJin[nowIdx] = value;
      this.setData({nianJin:nianJin});
      return;
    }else{ 
       wx.showToast({
         title: '请正确输入每月年金缴纳额！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       nianJin[nowIdx] = '';
       this.setData({nianJin:nianJin});
       return;
    }
  },

  onBussinessHealth(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var bussinessHealth = this.data.bussinessHealth;
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      bussinessHealth[nowIdx] = value;
      this.setData({bussinessHealth:bussinessHealth});
      return;
    }else{
       wx.showToast({
         title: '请正确输入每月商业健康险缴纳额！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       bussinessHealth[nowIdx] = '';
       this.setData({bussinessHealth:bussinessHealth});
       return;
    }
  },

  onGeRenYangLaoJin(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var bussinessHealth = this.data.yangLaoJin;
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      bussinessHealth[nowIdx] = value;
      this.setData({yangLaoJin:bussinessHealth});
      return;
    }else{
       wx.showToast({
         title: '请正确输入每月个人养老金缴纳额！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       bussinessHealth[nowIdx] = '';
       this.setData({yangLaoJin:bussinessHealth});
       return;
    }
  },

  onOther(e){
    var nowIdx=e.currentTarget.dataset.idx;
    var value = e.detail.value;
    var other = this.data.other;
    if(/^(0|[1-9][0-9]*)$/.test(value) || /^([1-9][0-9]*\.)$/.test(value) || /^([1-9][0-9]*)+(\.[0-9]{1,2})?$/.test(value)){
      other[nowIdx] = value;
      this.setData({other:other});
      return;
    }else{
       wx.showToast({
         title: '请正确输入每月个人养老金缴纳额！\r\n(仅数字，最多2位小数)',
         icon:'none'
       });
       other[nowIdx] = '';
       this.setData({other:other});
       return;
    }
  },

  btnNianJin(e){
    wx.showModal({
      title: '关于年金',
      showCancel:false,
      content: '年金：包括企业年金和职业年金，在不超过本人缴费工资计税基数的4%内，个人缴纳部分从应纳税所得额中扣除。大部分企业不缴纳年金，请确认工资中是否含有该部分。',
    })
     return false;
  },

  btnBussinessHealth(e){
    wx.showModal({
      title: '关于商业健康险',
      showCancel:false,
      content: '商业健康险：单位统一为员工购买的符合规定的商业健康保险产品支出，允许在计算个税时进行税前扣除，按月扣除限额200元/月。另：个人购买的仅支持按年扣除。',
    })
     return false;
  },

  btnGeRenYangLaoJin(e){
    wx.showModal({
      title: '关于个人养老金',
      showCancel:false,
      content: '个人养老金：你自己往个人养老金账户中存款，在综合所得或经营所得中可以据实扣除，扣除限额12000元/年（1000元/月）。另：税延养老保险也在此处填写，扣除标准相同。',
    })
     return false;
  },
  btnOther(e){
    wx.showModal({
      title: '关于其他',
      showCancel:false,
      content: '其他：其他未在上面列明的按月扣除项，可以在此处填写。',
    })
     return false;
  },

  onCompute(){
    var val = this.calOtherCount();
    // app.globalData.anotherStart = this.data.anotherStart;
    // app.globalData.anotherEnd = this.data.anotherEnd;
    // app.globalData.nianJin = this.data.nianJin;
    // app.globalData.bussinessHealth = this.data.bussinessHealth;
    // app.globalData.yangLaoJin = this.data.yangLaoJin;
    // app.globalData.other = this.data.other;
    if(val < 0){
      wx.showToast({
        title: '请正确填写！\r\n1.时间区间不能有重合\r\n2.时间区间需填写完整。',
        icon:'none',
        duration: 3000
      });
      return;
    }
    var value = this.data.totalAnother;
    const anotherBox   = JSON.stringify(this.data.checkbox)
    const anotherStart  = JSON.stringify(this.data.startDate)
    const anotherEnd  = JSON.stringify(this.data.endDate)
    const nianJin   = JSON.stringify(this.data.nianJin)
    const bussinessHealth   = JSON.stringify(this.data.bussinessHealth)
    const yangLaoJin = JSON.stringify(this.data.yangLaoJin)
    const other = JSON.stringify(this.data.other)

    wx.setStorageSync('anotherBox',anotherBox);
    wx.setStorageSync('anotherStart',anotherStart);
    wx.setStorageSync('anotherEnd',anotherEnd);
    wx.setStorageSync('nianJin',nianJin);
    wx.setStorageSync('bussinessHealth',bussinessHealth);
    wx.setStorageSync('yangLaoJin',yangLaoJin);
    wx.setStorageSync('other',other);

    wx.showToast({
      title: '计算成功！',
      icon: 'sucess',
      duration: 2000,
      success: (res)=> {
        setTimeout(function() {
          let pages = getCurrentPages();//当前页面
          let prevPage = pages[pages.length - 2 ];
          prevPage.setData({
            // securate:value,
            // secondSecurity:that.data.sbStandard,
            another:value
          });
          wx.navigateBack({
            delta: 1 
          })
        }, 2000);
      }
  });
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.showShareMenu({
      withShareTicket:true,
      menus:["shareAppMessage",'shareTimeline']});
    const mon = options.calDate;
    this.setData({calDate:mon});
    console.log(mon);
    const year = mon.split("-")
    this.setData({nowYear:year[0]});
  },

  formReset:function(){
    this.setData({
    checkbox:[1],
    totalAnother:'0.00',
    endDate:['结束时间'],
    startDate:['开始时间'],
    nianJin:[''],
    bussinessHealth:[''],
    yangLaoJin:[''],
    other:['']
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    var value = wx.getStorageSync('anotherBox');
    if (value) {
      that.setData({checkbox:JSON.parse(value)});
    }
    value = wx.getStorageSync('anotherStart');
    if (value) {
      that.setData({startDate:JSON.parse(value)});
    }
    value = wx.getStorageSync('anotherEnd');
    if (value) {
      that.setData({endDate:JSON.parse(value)});
    }
    value = wx.getStorageSync('nianJin');
    if (value) {
      that.setData({nianJin:JSON.parse(value)});
    }
    value = wx.getStorageSync('bussinessHealth');
    if (value) {
      that.setData({bussinessHealth:JSON.parse(value)});
    }
    value = wx.getStorageSync('yangLaoJin');
    if (value) {
      that.setData({yangLaoJin:JSON.parse(value)});
    }
    value = wx.getStorageSync('other');
    if (value) {
      that.setData({other:JSON.parse(value)});
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '答哥算税计算器',
      path: '/pages/index/index'
    }
  }
})